//获取系统PATH
var HOST = location.href.substr(0, location.href.indexOf("/Home"));

/**
 * 点击更换验证码图片
 */
$("#verify-image").click(function () {
    var actionName = "verify/";
    var time = new Date().getTime();
    $(this).attr({
        "src": actionName + time
    })
});

/**
 *  Ajax表单提交
 */
$(document).on("submit", ".ajax-form", function (e) {
    var submitButton = $(this).find("button[type=submit]");
    submitButton.attr("disabled", "disabled").text("正在提交");
    e.preventDefault();
    var action = $(this).attr("action");
    var method = $(this).attr("method");

    $.ajax({
        url: action,
        method: method,
        data: $(this).serialize(),
        success: function (data) {
            if (data.code == undefined) {
                submitButton.removeAttr("disabled").text("保存");
                new $.zui.Messager(data, {type: "warning", time: 2500}).show();
                return;
            }
            var type = (data.code == 200) ? "success" : "warning";
            new $.zui.Messager(data.msg, {type: type, time: 2500}).show();
            if (data.code == 200) {
                setTimeout(function () {
                    if (data.jumpUrl != "") {
                        window.location.href = data.jumpUrl;
                    }
                    else {
                        location.reload();
                    }
                }, 2500);
            }
            else {
                submitButton.removeAttr("disabled").text("保存");
            }
        },
        error: function () {
            submitButton.removeAttr("disabled").text("保存");
            new $.zui.Messager("系统错误,请稍后重试或联系管理员。", {type: "danger", time: 2500}).show();
        }
    })
});

/**
 * Ajax删除
 */
$(document).on("click", ".ajax-delete", function (e) {
    e.preventDefault();
    var href = $(this).attr("href");
    var message = $(this).data("msg");
    bootbox.confirm(message, function (result) {
        if (result) {
            $.ajax({
                url: href,
                method: "get",
                success: function (data) {
                    if (data.code == undefined) {
                        new $.zui.Messager(data, {type: "warning", time: 2500}).show();
                        return;
                    }
                    var type = (data.code == 200) ? "success" : "warning";
                    new $.zui.Messager(data.msg, {type: type, time: 2500}).show();
                    if (data.code == 200) {
                        setTimeout(function () {
                            if (data.jumpUrl != "") {
                                window.location.href = data.jumpUrl;
                            }
                            else {
                                location.reload();
                            }
                        }, 2500);
                    }
                },
                error: function () {
                    new $.zui.Messager("网络错误,请稍后重试或联系管理员。", {type: "danger", time: 2500}).show();
                }
            })
        }
    });
});

/**
 * 表单验证
 */
$(function () {
    $(".form-need-validate").validationEngine('attach', {
        promptPosition: 'centerRight',
        scroll: false,
        validationEventTrigger: null
    });
});

/**
 * 省市两级联动
 */
$(document).on("change", "select#select_province", function () {
    var provinceId = $(this).val();
    $.ajax({
        type: 'get',
        url: HOST + "/Home/Common/getCityByPid",
        data: 'pid=' + provinceId,
        success: function (city) {
            var str = '';
            for (var i = 0; i < city.length; i++) {
                str += "<option value=" + city[i].area_id + ">" + city[i].area_name + "</option>";
            }
            if (str == '') {
                str = "<option value=''>请选择</option>";
            }
            $("select#select_city").html(str);
        }
    });
});

/**
 * 发送验证码
 */
$(document).on("click", "#tel_code", function () {
    var button = $(this);
    var telephone = $('input[name=telephone]').val();
    $.ajax({
        type: 'get',
        url: HOST + "/Home/Common/sendCode",
        data: 'telephone=' + telephone,
        success: function (data) {
            if (data.code == 200) {
                new $.zui.Messager(data.msg, {type: "success", time: 2500}).show();
                //禁用按钮,并显示倒计时
                button.attr("disabled", "disabled");
                var time = 60;
                var disableButton = setInterval(function () {
                    time--;
                    button.text("(" + time + ")");
                    if (time == 0) {
                        clearInterval(disableButton);
                        button.text("获取");
                        button.removeAttr("disabled");
                    }
                }, 1000);
            }
            else {
                new $.zui.Messager(data.msg, {type: "danger", time: 2500}).show();
            }
        }
    });
});

/**
 * 选择日期
 */
$(".form-date").datetimepicker({
    language: "zh-CN",
    weekStart: 1,
    todayBtn: 1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 2,
    minView: 2,
    forceParse: 0,
    format: "yyyy-mm-dd"
});
$(".form-datetime").datetimepicker(
    {
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        format: "yyyy-mm-dd hh:ii:ss"
    });

/**
 * 车辆品牌型号两级联动
 */
$(document).on("change", "select#select_brand", function () {
    var brandId = $(this).val();
    $.ajax({
        type: 'get',
        url: HOST + "/Home/Common/getCarModelByPid",
        data: 'pid=' + brandId,
        success: function (model) {
            var str = '';
            for (var i = 0; i < model.length; i++) {
                str += "<option value=" + model[i].models_id + ">" + model[i].models_name + "</option>";
            }
            if (str == '') {
                str = "<option value=''>请选择型号</option>";
            }
            $("select#select_model").html(str);
        }
    });
});

/**
 * 是否贷款车值和贷款类型的显示隐藏联动关系
 */
$(function () {
    //刷新页面时根据当前值(是否为贷款车)判断贷款类型隐藏或显示
    var isLoan = $("input[name=is_loan]:checked").val();
    if (isLoan == 0) {
        $("#mortgage_type").hide();
    } else {
        $("#mortgage_type").show();
    }
    //点击事件，贷款类型隐藏或显示
    $('input[name=is_loan]').click(function () {
        var isLoan = $(this).val();
        if (isLoan == 0) {
            $("#mortgage_type").hide();
        } else {
            $("#mortgage_type").show();
        }
    });
    //批量上传
});

/**
 * jquery file upload插件上传文件到临时目录
 */
$(function () {
    'use strict';
    $("#fileUpload").fileupload(fileUploadOptions);
});

//jquery-file-upload插件初始化插件
var fileUploadOptions = {
    url: HOST + "/Home/Common/uploadFiles",
    dataType: "json",
    add: function (e, result) {
        $("#upload_progress").css("width", "0%");
        result.submit();
    },
    progressall: function (e, result) {
        var progress = parseInt(result.loaded / result.total * 100, 10);
        $("#upload_progress").css("width", progress + "%");
    },
    done: function (e, result) {
        //上传失败,则提示失败信息
        if (result.result.code != 200) {
            $("#fileUpload").removeAttr("disabled");
            $(".btn-success")
                .attr("style", "margin-left: 0px")
                .find("span").text("重新选择")
                .parents(".form-group").next().find("#upload_progress").css("width", "0%");
            $('#upload_progress').css("width", "0%");
            new $.zui.Messager(result.result.msg, {type: "warning", time: 2500}).show();
            return;
        }
        var files = result.result.data;
        var savename = files[0]["savename"];
        var savepath = files[0]["savepath"];
        var uploadfilepath = "./Public/Uploads/Temporary/" + savepath + savename;
        //添加图片临时路径到隐藏域
        var hiddenArea = "<input type=\"hidden\" name=\"filesurl[]\" value=\"" + uploadfilepath + "\" />";
        //组织已上传文件列表
        var previewTd = "<td class='col-md-2'>";
        if (isImage(files[0]['type'])) {
            previewTd += "<image src='" + HOST + "/Public/Uploads/Temporary/" + encodeURIComponent(savename) + "'>";
        }
        else {
            previewTd += "<image src='" + HOST + "/Public/images/files.png'>";
        }
        previewTd += "</td>";
        var filenameTd = "<td class='col-md-9'>" + result.files[0].name + "</td>";
        var buttonTd = "<td class='col-md-1'><button type='button' class='btn btn-warning remove-file' data-file-name='" + savename + "'>删除</button></td>";
        var tr = "<tr>" + previewTd + filenameTd + buttonTd + hiddenArea + "</tr>";
        //显示文件列表
        $(".file-list-table").append(tr);
        $(".file-list-table").removeClass("hidden");
    }
};

/**
 * 文件列表中删除文件
 */
$(document).on("click", ".remove-file", function () {
    var that = this;
    var filename = $(that).data("file-name");
    if (filename != '') {
        $.ajax({
            type: 'get',
            url: HOST + "/Home/Common/removeTempFile",
            data: 'filename=' + filename,
            success: function (result) {
                var msgType = (result.code == 200) ? "success" : "warning";
                $(that).parent().parent().remove();
                $('#fileUpload').removeAttr("disabled");
                $(".btn-success")
                    .attr("style", "margin-left: 20px")
                    .find("span").text("重新选择")
                $(".form-group").next().find(".progress-bar").css("width", "0%");
                $('#upload_progress').css("width", "0%");
                new $.zui.Messager(result.msg, {type: msgType, time: 2500}).show();
            },
            error: function () {
                new $.zui.Messager('移除失败', {type: "warning", time: 2500}).show();
            }
        })
    }
});

/**
 * 判断文件类型是否为图片
 * @param fileType string mime文件类型
 * @returns {boolean}
 */
function isImage(fileType) {
    var types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'];
    return ($.inArray(fileType, types) != -1);
}

/**
 * 文件列表中删除已上传的文件
 */
$(document).on("click", ".delete-uploaded-file", function () {
    var that = this;
    var id = $(that).data("attachment-id");
    if (id != '') {
        $.ajax({
            type: 'get',
            url: HOST + "/Home/Common/deleteCarAttachmentById",
            data: 'attachment_id=' + id,
            success: function (result) {
                var msgType = (result.code == 200) ? "success" : "warning";
                $(that).parent().parent().remove();
                new $.zui.Messager(result.msg, {type: msgType, time: 2500}).show();
            },
            error: function () {
                new $.zui.Messager('删除失败', {type: "warning", time: 2500}).show();
            }
        })
    }
});

/**
 * 点击后退
 */
$(document).on("click", ".go-back", function () {
    history.back();
});

/**
 * 车牌号码检测
 */
$(document).on("blur", ".check-platenumber-format", function () {
    var plateNumber = $(this).val();
    var regex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/i;
    var plateNumberStatus = regex.test(plateNumber);
    if (!plateNumberStatus) {
        new $.zui.Messager('请输入正确的车牌号码,例如:沪A00001', {type: "warning", time: 2500}).show();
    }
});
/*
 * 上传,修改放款单字段验证
 */
$(document).on("click", '.checkPay', function () {
    var other_telephone = $('#other_telephone').val();
    var manager_bankcard = $('#manager_bankcard').val();
    var other_contacter = $('#other_contacter').val();
    var manager_bankcard_name = $('#manager_bankcard_name').val();
    var manager_bank = $('#manager_bank').val();
    var regex = /^1[34578]\d{9}$/;
    var bankcard = /^(\d{16}|\d{19})$/;
    var regex_name =  /^[\u4e00-\u9fa5]+$/;
    if (manager_bankcard != 0) {
        if (!bankcard.test(manager_bankcard)) {
            new $.zui.Messager('客户经理银行卡号格式错误', {type: "warning", time: 2500}).show();
            return false;
        }
    }
    if (manager_bankcard_name != 0) {
        if(!regex_name.test(manager_bankcard_name)){
            new $.zui.Messager('经理银行卡开户名请输入汉字', {type: "warning", time: 2500}).show();
            return false;
        }
    }
    if (manager_bank != 0) {
        if(!regex_name.test(manager_bank)){
            new $.zui.Messager('客户经理开户行请输入汉字', {type: "warning", time: 2500}).show();
            return false;
        }
    }
    if (other_contacter != 0) {
        if (!regex_name.test(other_contacter)) {
            new $.zui.Messager('备用联系人姓名请输入汉字', {type: "warning", time: 2500}).show();
            return false;
        }
    }
    if (other_telephone != 0) {
        if (!regex.test(other_telephone)) {
            new $.zui.Messager('备用联系人手机号码格式错误', {type: "warning", time: 2500}).show();
            return false;
        }
    }

    if (other_telephone != 0 && other_contacter == 0 || other_telephone == 0 && other_contacter != 0) {
        new $.zui.Messager('请备用联系人填写完整信息', {type: "warning", time: 2500}).show();
        return false;
    }
});